//
//  ZCAssignCodeDetailViewController.m
//  ZhiChe-Wms
//
//  Created by 高睿婕 on 2018/8/20.
//  Copyright © 2018年 Regina. All rights reserved.
//

#import "ZCAssignCodeDetailViewController.h"
#import "ZCTaskTotalNumTableViewCell.h"
#import "UWRQViewController.h"
#import "ZCAssignCodeModel.h"
#import "ZCAbnormalMissingTableViewCell.h"
#import "ZCAssignCodeEditVinViewController.h"
#import "ZCAssignCodeEditVehicleViewController.h"


static NSString *codeDetailCellID = @"ZCTaskTotalNumTableViewCell";
static NSString *vinEditCellID = @"ZCAbnormalMissingTableViewCell";

@interface ZCAssignCodeDetailViewController ()<UITableViewDelegate, UITableViewDataSource, uwRQDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIButton *finishButton;
@property (nonatomic, strong) ZCAssignCodeDetailModel *detailModel;
@property (nonatomic, strong) MBProgressHUD *hud;
@property (nonatomic, assign) BOOL isScan;
@end

@implementation ZCAssignCodeDetailViewController
#pragma mark - 懒加载
- (UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREENWIDTH, space(90*6)) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.scrollEnabled = NO;
        if (@available(iOS 11.0, *)) {
            _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
            _tableView.contentInset = UIEdgeInsetsMake(64, 0, 0, 0);
            _tableView.scrollIndicatorInsets = _tableView.contentInset;
            _tableView.estimatedRowHeight = 0;
            _tableView.estimatedSectionFooterHeight = 0;
            _tableView.estimatedSectionHeaderHeight = 0;
        }
        [_tableView registerClass:[ZCTaskTotalNumTableViewCell class] forCellReuseIdentifier:codeDetailCellID];
        [_tableView registerClass:[ZCAbnormalMissingTableViewCell class] forCellReuseIdentifier:vinEditCellID];
    }
    return _tableView;
}

- (UIButton *)finishButton {
    if (!_finishButton) {
        _finishButton = [[UIButton alloc] init];
        [_finishButton setTitle:@"赋码" forState:UIControlStateNormal];
        [_finishButton setTitleColor:ZCColor(0xffffff, 1) forState:UIControlStateNormal];
        _finishButton.titleLabel.font = [UIFont systemFontOfSize:FontSize(30)];
        [_finishButton setBackgroundColor:ZCColor(0xff8213, 1)];
        _finishButton.layer.masksToBounds = YES;
        _finishButton.layer.cornerRadius = space(6);
        [_finishButton addTarget:self action:@selector(assignCode:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _finishButton;
}

#pragma mark - 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 50, 30)];
    [leftButton setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [leftButton addTarget:self action:@selector(backToHome) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
    self.navigationItem.title = @"赋码";
    self.view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [self.view addSubview:self.finishButton];
    [self updateViewConstraints];
    self.isScan = NO;
    self.hud = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:self.hud];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    if (!self.isScan) {
        [self loadData];
//    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.hud hideAnimated:YES];
    self.hud.mode = MBProgressHUDModeIndeterminate;
}

#pragma mark - 按钮点击
- (void)backToHome {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)assignCode:(UIButton *)sender {
    self.isScan = YES;
    UWRQViewController *rqVC = [[UWRQViewController alloc] init];
    rqVC.delegate = self;
    [self.navigationController pushViewController:rqVC animated:YES];
}

#pragma mark - uwRQDelegate
- (void)uwRQFinshedScan:(NSString *)result {
    NSArray *arr = [result componentsSeparatedByString:@","];
    NSString *keyId = [arr firstObject];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:@(0) forKey:@"taskType"];
    [param setObject:keyId forKey:@"qrCode"];
    [param setObject:self.detailModel.releaseId forKey:@"releaseId"];
//    NSLog(@"%@",self.detailModel.releaseId);
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:BindQRCode params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = @"赋码成功";
                [weakSelf.hud hideAnimated:YES afterDelay:SuccessTime];
                [weakSelf.finishButton setTitle:@"重新赋码" forState:UIControlStateNormal];
                [weakSelf loadData];
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - 网络请求
- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:self.releaseId forKey:@"id"];
    [param setObject:@(0) forKey:@"taskType"];
    

    [self.hud showAnimated:YES];
    __weak typeof(self)weakSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        [ZCHttpTool postWithURL:TaskDetail params:param success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            if ([responseObject[@"success"] boolValue]) {
                [weakSelf.hud hideAnimated:YES];
                NSDictionary *dic = responseObject[@"data"];
                weakSelf.detailModel = [ZCAssignCodeDetailModel yy_modelWithDictionary:dic];
                [weakSelf.tableView reloadData];
                if (weakSelf.detailModel.qrCode.length > 0) {
                    [weakSelf.finishButton setTitle:@"重新赋码" forState:UIControlStateNormal];
                }
            }else {
                weakSelf.hud.mode = MBProgressHUDModeText;
                weakSelf.hud.label.text = responseObject[@"message"];
                [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
            }
            
        } failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
            weakSelf.hud.mode = MBProgressHUDModeText;
            weakSelf.hud.label.text = error.localizedDescription;
            [weakSelf.hud hideAnimated:YES afterDelay:HudTime];
        }];
    });
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1 || indexPath.row == 2) {
        ZCAbnormalMissingTableViewCell *vinCell = [tableView dequeueReusableCellWithIdentifier:vinEditCellID forIndexPath:indexPath];
        vinCell.selectionStyle = UITableViewCellSelectionStyleNone;
        vinCell.contentColor = ZCColor(0x000000, 0.87);
        if (indexPath.row == 1) {
            vinCell.title = @"车架号";
            vinCell.content = self.detailModel.vin;
            vinCell.canSelected = self.detailModel.vin.length > 0 ? NO : YES;
        }else {
            vinCell.title = @"车型";
            vinCell.canSelected = YES;
            vinCell.content = self.detailModel.vehicle;
        }
        
        return vinCell;
    }else {
        ZCTaskTotalNumTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:codeDetailCellID forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.titleColor = ZCColor(0x000000, 0.54);
        cell.titleFont = [UIFont systemFontOfSize:FontSize(28)];
        cell.contentColor = ZCColor(0x000000, 0.87);
        cell.contentFont = [UIFont systemFontOfSize:FontSize(28)];
        cell.line = YES;
        if (indexPath.row == 0) {
            cell.title = @"订单号";
            cell.content = self.detailModel.orderNo;
           
        }else {
            cell.title = @"二维码";
            cell.content = self.detailModel.qrCode;
        }
        return cell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return space(90);
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] init];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1 && self.detailModel.vin.length == 0) {
        ZCAssignCodeEditVinViewController *editVC = [[ZCAssignCodeEditVinViewController alloc] init];
        editVC.key = self.releaseId;
        editVC.name = @"vin";
        [self.navigationController pushViewController:editVC animated:YES];
    }else if (indexPath.row == 2) {
        ZCAssignCodeEditVehicleViewController *vehicleVC = [[ZCAssignCodeEditVehicleViewController alloc] init];
        vehicleVC.key = self.detailModel.releaseId;
        [self.navigationController pushViewController:vehicleVC animated:YES];
    }
}

#pragma mark - 布局
- (void)updateViewConstraints {
    [super updateViewConstraints];
    __weak typeof(self)weakSelf = self;
    [_finishButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(weakSelf.view.mas_left).offset(space(40));
        make.right.equalTo(weakSelf.view.mas_right).offset(-space(40));
        make.height.mas_equalTo(space(90));
        make.top.equalTo(weakSelf.tableView.mas_bottom).offset(space(300));
    }];
}

@end
